﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 蓝牙注册工具.BLL
{
    public class PortBLL
    {
        public static SerialPort serialPort1 = new SerialPort();
        public static SerialPort serialPort2 = new SerialPort();
        public static SerialPort serialPort3 = new SerialPort();
        public static SerialPort serialPort4 = new SerialPort();
        public static SerialPort serialPortBt = new SerialPort();
        /// <summary>
        /// 获取设备串口
        /// </summary>
        public static ObservableCollection <string> GetPorts()
        {
            try
            {
                ObservableCollection<string> Ports = new ObservableCollection<string>();
                string[] ports = BtLabelTool.PortHelper.GetPorts();
                foreach (var item in ports)
                {
                    Ports.Add(item);
                }
                return Ports;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        public static bool InitPort(SerialPort serialPort, string port, int baudRate)
        {
            try
            {
                if (GetPorts().Contains(port) == false)
                {
                    return false;
                }

                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }
                BtLabelTool.PortHelper.InitPort(serialPort, port, baudRate);
                serialPort.Open();

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void InitPorts()
        {
            try
            {
                InitPort(serialPort1, MainWindow.config.Channel1Portname, 115200);
                InitPort(serialPort2, MainWindow.config.Channel2Portname, 115200);
                InitPort(serialPort3, MainWindow.config.Channel3Portname, 115200);
                InitPort(serialPort4, MainWindow.config.Channel4Portname, 115200);
                InitPort(serialPortBt, MainWindow.config.BtPortname, 115200);
            }
            catch (Exception ex)
            {
                HandyControl.Controls.Growl.Error(ex.Message);
            }
        }
    }
}
